package jp.tonosama.komoki.SimpleGolfScorer2;

import java.io.File;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Komoki
 */
public class TitleMenuManager {

    /**  */
    private static final String TAG = TitleMenuManager.class.getSimpleName();
    /**  */
    private static final boolean DEBUG = false;
    /**  */
    private Context mContext;
    /**  */
    private static final String BACKUP_DIR_NAME = "SmartGolfScore/backup";
    /**  */
    private static final int FIRST_ID = Menu.FIRST;
    /**  */
    private static final String PREF_SORT_TYPE_SETTING = "PREF_SORT_TYPE_SETTING";
    /**  */
    private static final String PREF_SORT_TYPE_KEY = "PREF_SORT_TYPE_KEY";
    /**  */
    private static final String MARKET_PACKAGE_NAME = "com.android.vending";

    /**
     * コンストラクタ
     */
    public TitleMenuManager(final Context context) {
        mContext = context;
    }

    /**
     * @param item
     * @return
     */
    public boolean onOptionsItemSelected(final MenuItem item) {
        if (DEBUG) {
            Log.d(TAG, "onOptionsItemSelected item:" + item.toString());
        }
        boolean ret = true;
        switch (item.getItemId()) {
        case FIRST_ID + 2:
            // 並び順変更
            actionChangeSort();
            break;
        case FIRST_ID:
            // データバックアップ
            actionDataBackup();
            break;
        case FIRST_ID + 1:
            // データリストア
            actionDataRestore();
            break;
        case FIRST_ID + 3: // history
            break;
        case FIRST_ID + 4: // about
            // about
            actionAbout();
            break;
        default:
            ret = false;
            break;
        }
        return ret;
    }

    /**
     * actionAbout
     */
    private void actionAbout() {

        final Resources res = mContext.getResources();
        String mAboutDialogTitle = res.getString(R.string.app_name);
        String mAboutDialogMsg1 = "";
        mAboutDialogMsg1 += res.getString(R.string.about_author) + " ";
        mAboutDialogMsg1 += res.getString(R.string.about_author_name) + "\n";
        mAboutDialogMsg1 += res.getString(R.string.about_email) + " ";
        mAboutDialogMsg1 += res.getString(R.string.about_email_address);

        String mAboutDialogMsg2 = "\n";
        mAboutDialogMsg2 += res.getString(R.string.about_introduction) + "\n\n";
        mAboutDialogMsg2 += res.getString(R.string.about_function_summary);

        // mod for ver 2.0.1 -> S
        TextView tv1 = new TextView(mContext);
        tv1.setTextSize(18);
        tv1.setAutoLinkMask(Linkify.EMAIL_ADDRESSES);
        tv1.setText(mAboutDialogMsg1);

        TextView tv2 = new TextView(mContext);
        tv2.setTextSize(18);
        tv2.setText(mAboutDialogMsg2);

        LinearLayout mAboutLinearLayout = new LinearLayout(mContext);
        mAboutLinearLayout.setOrientation(LinearLayout.VERTICAL);
        mAboutLinearLayout.setPadding(5, 0, 5, 0);
        mAboutLinearLayout.addView(tv1, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mAboutLinearLayout.addView(tv2, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        ScrollView wrapScrollView = new ScrollView(mContext);
        wrapScrollView.addView(mAboutLinearLayout, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        // mod for ver 2.0.1 -> E

        showAboutDialog(mAboutDialogTitle, wrapScrollView);
    }

    /**
     * showAboutDialog
     * 
     * @param title ダイアログタイトル
     * @param view ダイアログView
     */
    private void showAboutDialog(final String title, final View view) {
        final Resources res = mContext.getResources();
        AlertDialog.Builder aboutDialog = new AlertDialog.Builder(mContext);
        aboutDialog.setIcon(R.drawable.icon);
        try {
            String dialogTitle = title
                    + "\nver "
                    + mContext.getPackageManager().getPackageInfo(mContext.getPackageName(),
                            PackageManager.GET_META_DATA).versionName;
            aboutDialog.setTitle(dialogTitle);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        aboutDialog.setView(view);
        aboutDialog.setPositiveButton(R.string.about_app_detail_btn,
                new DialogInterface.OnClickListener() {

                    public void onClick(final DialogInterface dialog, final int which) {
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setPackage(MARKET_PACKAGE_NAME);
                        intent.setData(Uri.parse(res.getString(R.string.about_url_market)));
                        mContext.startActivity(intent);
                    }
                });
        aboutDialog.setNeutralButton(R.string.about_app_share_btn,
                new DialogInterface.OnClickListener() {

                    public void onClick(final DialogInterface dialog, final int which) {
                        Intent intent = new Intent(Intent.ACTION_SEND);
                        intent.setType("text/*");
                        intent.putExtra(
                                Intent.EXTRA_TEXT,
                                res.getString(R.string.about_introduction) + "\n\n"
                                        + res.getString(R.string.about_url_market));
                        mContext.startActivity(Intent.createChooser(intent,
                                res.getString(R.string.about_app_share_btn)));
                    }
                });
        aboutDialog.show();
    }

    /**
     * actionDataRestore
     */
    private void actionDataRestore() {

        Resources res = mContext.getResources();
        final File mBkFileDir = new File(Environment.getExternalStorageDirectory() + "/"
                + BACKUP_DIR_NAME);
        if (!mBkFileDir.exists()) {
            Toast.makeText(mContext, res.getString(R.string.toast_backup_not_found),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        final String[] mBkFileList = mBkFileDir.list();
        if (mBkFileList == null || mBkFileList.length == 0) {
            Toast.makeText(mContext, res.getString(R.string.toast_backup_not_found),
                    Toast.LENGTH_SHORT).show();
            return;
        }
        AlertDialog.Builder restoreDialog = new AlertDialog.Builder(mContext);
        restoreDialog.setIcon(R.drawable.ic_menu_restore);
        restoreDialog.setTitle(res.getString(R.string.dlg_restore_title));
        restoreDialog.setItems(mBkFileList, new OnClickListener() {

            public void onClick(final DialogInterface dialog, final int item) {
                ((MainTitle) mContext).loadBackupData(mBkFileDir.toString(), mBkFileList[item],
                        mContext);
            }
        });
        restoreDialog.show();
    }

    /**
     * actionDataBackup
     */
    private void actionDataBackup() {

        Resources res = mContext.getResources();
        AlertDialog.Builder backupDialog = new AlertDialog.Builder(mContext);
        backupDialog.setIcon(R.drawable.ic_menu_save);
        backupDialog.setTitle(res.getString(R.string.dlg_backup_title));
        backupDialog.setMessage(res.getString(R.string.dlg_backup_guide_msg));
        backupDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

            public void onClick(final DialogInterface dialog, final int which) {
                ((MainTitle) mContext).outputBackupData(mContext);
            }
        });
        backupDialog.setNegativeButton(android.R.string.cancel,
                new DialogInterface.OnClickListener() {

                    public void onClick(final DialogInterface dialog, final int which) {
                        //
                    }
                });
        backupDialog.show();
    }

    /**
     * actionChangeSort
     */
    private void actionChangeSort() {

        Resources res = mContext.getResources();
        SharedPreferences pref = mContext.getSharedPreferences(PREF_SORT_TYPE_SETTING,
                Context.MODE_PRIVATE);
        int mSortType = pref.getInt(PREF_SORT_TYPE_KEY, 0);
        String[] sortNames = { res.getString(R.string.menu_sort_default),
                res.getString(R.string.menu_sort_name_descending),
                res.getString(R.string.menu_sort_name_ascending) };
        AlertDialog.Builder mDialog = new AlertDialog.Builder(mContext);
        mDialog.setTitle(res.getString(R.string.menu_sort));
        mDialog.setSingleChoiceItems(sortNames, mSortType, new OnClickListener() {

            public void onClick(final DialogInterface dialog, final int item) {
                dialog.dismiss();
                SharedPreferences mSortPref = mContext.getSharedPreferences(PREF_SORT_TYPE_SETTING,
                        Context.MODE_PRIVATE);
                Editor mEditor = mSortPref.edit();
                mEditor.putInt(PREF_SORT_TYPE_KEY, item);
                mEditor.commit();
                ((MainTitle) mContext).reStartActivity();
            }
        });
        mDialog.create().show();
    }
}